/********************************************************************
 * Filename:	BitOps.c
 * Description:	s
 *				Also holds functions to manipulate metatable entries
 * 
 * Group 2:		nachOS
 * Author(s):	Jan Durakiewicz
 * 
 * Class:		CSE 325
 * Instructor:	David Duggan
 * Assignment:	Lab #6 Page Replacement
 * Assigned:	4/2/2013
 * Due:			4/9/2013
 ********************************************************************/
#include "BitOps.h"

void init_masks(){
	addressMask = power_of_two(14) - 1; //00 followed by 14 1's
	allocMask = power_of_two(14);		//a 1 in the 15th bit
	validMask = power_of_two(15);		//a 1 in the 16th bit
}

/*-------------------------------------------------------------------------*/
void set_page_alloc(short unsigned int* entry, short unsigned int isAlloc){
	if(isAlloc == 1)
		*entry = *entry | allocMask;
	else
		*entry = *entry & ~(allocMask);
}

short unsigned int get_page_alloc(short unsigned int* entry){
	return (short unsigned int)((*entry & allocMask) >> 14);
}

/*-------------------------------------------------------------------------*/
void set_page_valid(short unsigned int* entry, short unsigned int isValid){
	if(isValid == 1)
		*entry = *entry | validMask;
	else
		*entry = *entry & ~(validMask);
}

short unsigned int get_page_valid(unsigned short int* entry){
	return (short unsigned int)((*entry & validMask) >> 15);
}

/*-------------------------------------------------------------------------*/
void set_page_address(short unsigned int* entry, short unsigned int address){
	if(address < 16384)
		*entry = (*entry & ~(addressMask)) | address;
}

short unsigned int get_page_address(short unsigned int* entry){
	return (short unsigned int)(*entry & addressMask);
}



short unsigned int power_of_two(short unsigned int exponent){
	if(exponent == 1)
		return (short unsigned int)2;
	else 
		return (short unsigned int)2 * power_of_two(exponent - 1);
}

void int_to_chars(unsigned int to_convert, unsigned char chars[3]){
	unsigned char mask =255;
	chars[2] = (to_convert >> 16) & mask;
	chars[1] = (to_convert >> 8) & mask;
	chars[0] = (to_convert) & mask;
}
